package com.shangye.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;

    private Map<String ,String> headers = new HashMap<>();

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            String line = redLine();
            System.out.println("请求行：" + line);

            while (true){
                line = redLine();
                if (line.isEmpty()){
                    break;
                }
                System.out.println("消息头：" + line);
                String[] split = line.split(":\\s");
                headers.put(split[0],split[1]);
            }

            System.out.println("headers:" +headers);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String redLine() throws IOException{
        InputStream inputStream = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char pre = 'a',cur = 'a';
        while ((d = inputStream.read())!=-1){
            cur = (char)d;
            if (pre==13&&cur==10){
                break;
            }
            pre = cur;
            builder.append(pre);
        }
        return builder.toString().trim();
    }

}
